use std::env::args;
use std::fs::{read_to_string, write};
use std::io::Result;

use ir::GenerateAsm;
use lalrpop_util::lalrpop_mod;

pub mod ast;
pub mod ir;

lalrpop_mod!(sysy);

fn main() -> Result<()> {
  let mut args = args();
  args.next();
  let mode = args.next().unwrap();
  let input = args.next().unwrap();
  args.next();
  let output = args.next().unwrap();

  // read input file
  let input = read_to_string(input)?;

  // invoke lexer to scan and parse the input
  let ast = sysy::CompUnitParser::new().parse(&input).unwrap();

  // for debug
  println!("{:#?}", ast);
  let koopa_ir = ast.dump_koopa();
  println!("{}", koopa_ir);

  if mode == "-koopa" {
    // write koopa-ir to file `output`
    write(output, koopa_ir)?;
  } else if mode == "-riscv" {
    // invoke koopa to translate string to koopa data structure
    let driver = koopa::front::Driver::from(koopa_ir);
    let program = driver.generate_program().unwrap();
    println!("{}", program.generate());
    // write riscv asm to file `output`
    // write(output, program.generate())?;
  } else {
    assert!(false, "invalid option (include: -koopa/riscv");
  }

  Ok(())
}
